#!/usr/bin/env bash
Target=huichexitong
Description=huichexitong
RestartInterval=10

function start_server()
{
	#set program directory
	Path="$(cd "$(dirname "$0")"; pwd)"

	#daemon script
	cd $Path
	ulimit -c unlimited
	while true
	do
		pid=$(pidof $Target)
		if [ -z "$pid" ]
		then
			$Path/$Target 
			echo "$Description将在$RestartInterval秒后重启..."
			sleep $RestartInterval
		else
			echo "$Description已运行,PID:$pid"
			break
		fi
	done
}

function get_ppid()
{
	echo $(ps -p $1 -o ppid=)
}

function stop_server()
{
	pid=$(pidof $Target)
	if [ -n "$pid" ]
	then
		ppid=$(get_ppid $pid)
		kill -9 $ppid
		kill -SIGINT $pid
	fi
}

function status_server()
{
	pid=$(pidof $Target)
	if [ -n "$pid" ]
	then
		echo "$Description已运行,PID:$pid"
	else
		echo "$Description未运行"
	fi
}

function install_server()
{
	#set program directory
	Path="$(cd "$(dirname "$0")"; pwd)"

	#chmod
	chmod 777 -R $Path

	#autorun script
	sed -i '/#wandaoapp-start/,/#wandaoapp-end/'d /etc/rc.local
	echo "#wandaoapp-start" >> /etc/rc.local
	echo "cd $Path" >> /etc/rc.local
	echo "chmod +x *" >> /etc/rc.local
	echo "./run.sh start & >/dev/null" >> /etc/rc.local
	echo "#wandaoapp-end" >> /etc/rc.local
}

function uninstall_server()
{
	rm -rf "/etc/ld.so.conf.d/$Target-x86_64.conf"
	ldconfig
	sed -i '/#wandaoapp-start/,/#wandaoapp-end/'d /etc/rc.local
}

case $1 in
start)
	start_server;;
stop)
	stop_server;;
status)
	status_server;;
install)
	install_server;;
uninstall)
	uninstall_server;;
*)
	echo "Usage: $0 {start|stop|status|install|uninstall}"
esac

